package zhr.store.filter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import zhr.store.common.BaseContext;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录过滤器
 */
@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    //路径匹配器
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求URL
        String uri = request.getRequestURI();
        //2.定义无需处理的URL
        String uris[] = {"/employee/login", "/user/login", "/user/sendMsg", "/employee/logout", "/user/logout","/backend/**", "/front/**"};
        //3.检查是否需要放行
        boolean check = checkURL(uri, uris);
        if (check) {
            filterChain.doFilter(request, response);
            return;
        }
        //4.判断是否为登录状态
        Object employee = request.getSession().getAttribute("employee");
        if (employee != null) {
            //获取id
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }
        Object user = request.getSession().getAttribute("user");
        if (user != null) {
            //获取id
            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);
            filterChain.doFilter(request, response);
            return;
        }
        //5.未登录响应客户端页面数据
        response.sendRedirect("/backend/page/login/login.html");
    }

    /**
     * 检查是否需要放行
     *
     * @param uri
     * @return
     */
    public boolean checkURL(String uri, String uris[]) {
        for (String checkUri : uris) {
            boolean match = PATH_MATCHER.match(checkUri, uri);
            if (match) {
                return true;
            }
        }
        return false;
    }
}
